package cn.com.shopec.erp.financing.dao.impl;

import java.math.BigInteger;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;
import cn.com.shopec.erp.common.orm.impl.HibernateEntityDao;
import cn.com.shopec.erp.common.page.PageFinder;
import cn.com.shopec.erp.common.page.PageQuery;
import cn.com.shopec.erp.common.utils.StringUtil;
import cn.com.shopec.erp.financing.dao.ISupplierSettlementDetailDao;
import cn.com.shopec.erp.financing.entity.SupplierSettlementDetail;
import cn.com.shopec.erp.financing.vo.SupplierSettlementVo;

@Repository
public class SupplierSettlementDetailDaoImpl extends HibernateEntityDao<SupplierSettlementDetail>
		implements ISupplierSettlementDetailDao {

	@Override
	public PageFinder supplierSettlementDetailPageList(SupplierSettlementVo supplierSettlementVo, PageQuery pageQuery) {
		String params = "";
		if (supplierSettlementVo != null) {
			if (StringUtil.isExist(supplierSettlementVo.getSettlementNo())) {
				params += " AND ssd.settlement_no ='" + supplierSettlementVo.getSettlementNo() + "'";
			}
		}
		String querysql = "SELECT ssd.id id,ssd.settlement_no settlementNo,ssd.po_no poNo,ssd.po_type poType,"
				+ "po.po_no ppoNo,po.totalPrice,po.supCode,po.supName,po.is_settled isSettled,po.returnQuantity "
				+ "FROM tbl_supplier_settlement_detail ssd " 
				+ "LEFT JOIN tbl_purchase_order po ON ssd.po_no=po.po_no "
				+ "WHERE ssd.po_type=1 " + params
				+ " UNION ALL "
				+ "SELECT ssd.id id,ssd.settlement_no settlementNo,ssd.po_no poNo,ssd.po_type poType,"
				+ "pro.poNo ppoNo,pro.totalPrice,pro.supCode,pro.supName,pro.is_settled isSettled,pro.returnQuantity "
				+ "FROM tbl_supplier_settlement_detail ssd "
				+ "LEFT JOIN tbl_purchase_return_order pro ON ssd.po_no=pro.puNo " 
				+ "WHERE ssd.po_type=2 " + params;
		
		String countsql = "select count(*) from tbl_supplier_settlement_detail ssd where 1=1 " + params;
		BigInteger count = (BigInteger) this.createSQLQuery(countsql).list().get(0);
		List list = getSession().createSQLQuery(querysql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP)
				.setFirstResult((pageQuery.getPage() - 1) * pageQuery.getPageSize())
				.setMaxResults(pageQuery.getPageSize()).list();
		PageFinder page = new PageFinder(pageQuery.getPage(), pageQuery.getPageSize(), count.intValue(), list);
		return page;

	}
	
	@Override
	public List findSettlementDetailByNo(SupplierSettlementDetail ssd){
		DetachedCriteria detachedCriteria = createCriteria();
		if (ssd != null) {
			if (StringUtil.isExist(ssd.getSettlementNo())) {
				detachedCriteria.add(Restrictions.eq("settlementNo", ssd.getSettlementNo()));
			}
		}
		detachedCriteria.addOrder(Order.desc("poNo"));
		return findByCriteria(detachedCriteria);
	}
}
